//
//  ComposeViewController.swift
//  JJWeibo
//
//  Created by JJ on 15/9/10.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
import ReactiveCocoa
import SVProgressHUD


private let JJStatusTextMaxLength=10
class ComposeViewController: UIViewController,UITextViewDelegate {

    private lazy var emoticonVC:EmoticonViewController=EmoticonViewController { [weak self](emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
        
    }
    private var toolBarBottomCons:NSLayoutConstraint?
    private var textViewBottomCons:NSLayoutConstraint?
    private var pictureViewHeightCons:NSLayoutConstraint?
    
    @objc private func send(){
        
        let status=textView.emoticonText
        let text=textView.emoticonText
        
        if text.characters.count > JJStatusTextMaxLength{
            
            SVProgressHUD.showErrorWithStatus("少发点有的没的", maskType: SVProgressHUDMaskType.Gradient)
            
            return
        }
        
        NetWorkTools.shareNetWorkTools.senStatus(status, image: pictureSelectorVC.pictures.last).subscribeNext({ (resualt) -> Void in
            
            }, error: { (error) -> Void in
                print(error)
                
                SVProgressHUD.showErrorWithStatus("发的啥")
            }) { () -> Void in
                self.close()
        }
        
    }
    
    @objc private func close(){
        
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func swichEmoticonKeyboard(){
        
        textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        textView.becomeFirstResponder()
    }
    
    override func loadView() {
        view=UIView()
        view.backgroundColor=UIColor.whiteColor()
        
        automaticallyAdjustsScrollViewInsets=false
        
        prepareNav()
        prepareToolBar()
        prepareTextView()
        preparePictureView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
      
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if pictureViewHeightCons?.constant==0{
            textView.becomeFirstResponder()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
   @objc private func keyBoardChanged(n:NSNotification){
    
        let curve=n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        let rect=n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        let duration=n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
    
        toolBarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y
        UIView.animateWithDuration(duration) { () -> Void in
            
            UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: curve)!)
            self.view.layoutIfNeeded()
    }
    }
    
    func textViewDidChange(textView: UITextView) {
        placeHolder.hidden=textView.hasText()
        navigationItem.rightBarButtonItem?.enabled=true
        
        let len = JJStatusTextMaxLength - textView.emoticonText.characters.count
        
        tipLable.text=String(len)
        tipLable.textColor = len > 0 ? UIColor.darkGrayColor() :UIColor.redColor()
    }
    
    private func preparePictureView(){
        view.insertSubview(pictureSelectorVC.view, belowSubview: toolBar)
        addChildViewController(pictureSelectorVC)
        
        let size = UIScreen.mainScreen().bounds.size
        let w = size.width
        let h:CGFloat = 0 //size.height * 0.6
        
       let cons = pictureSelectorVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: h))
        
        pictureViewHeightCons = pictureSelectorVC.view.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    private func prepareTextView(){
        view.addSubview(textView)
        let viewDic:[String:AnyObject]=["top":topLayoutGuide,"tb":toolBar,"tv":textView]
        textView.translatesAutoresizingMaskIntoConstraints=false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tv]-0-|", options: [], metrics: nil, views: viewDic))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[tv]", options: [], metrics: nil, views: viewDic))
        
        textViewBottomCons=NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        textView.addSubview(placeHolder)
        placeHolder.frame=CGRect(origin: CGPoint(x: 5, y: 8), size: placeHolder.bounds.size)
        
        view.addSubview(tipLable)
        
        tipLable.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -JJStatusCellMargin, y:-JJStatusCellMargin))
        
    }
    private func prepareToolBar(){
        
        view.addSubview(toolBar)
        toolBar.backgroundColor=UIColor(white: 0.8, alpha: 1.0)
        
        let w=UIScreen.mainScreen().bounds.width
       let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSizeMake(w, 44))
        toolBarBottomCons=toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        var items=[UIBarButtonItem]()
        let itemSetting=[["imageName":"compose_toolbar_picture","action":"selectPicture"],
            ["imageName":"compose_mentionbutton_background"],
            ["imageName":"compose_trendbutton_background"],
            ["imageName":"compose_emoticonbutton_background","action":"swichEmoticonKeyboard"],
            ["imageName":"compose_addbutton_background"]]
        
        for dic in itemSetting{
            
            items.append(UIBarButtonItem(imageName:dic["imageName"]!, target: self, actionName: dic["action"]))
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        toolBar.items=items
    }
    
    @objc private func selectPicture(){
        
        view.removeConstraint(textViewBottomCons!)
        textViewBottomCons=NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: pictureSelectorVC.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        textView.resignFirstResponder()
        pictureViewHeightCons?.constant=UIScreen.mainScreen().bounds.height * 0.6
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }

    private func prepareNav(){
        
        navigationItem.leftBarButtonItem=UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem=UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled=false
        
        let titleView=UIView(frame: CGRectMake(0, 0, 200, 32))
        let titleLable=UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontsize: 15)
        let nameLable=UILabel(title: UserAccountViewModel.sharedUserAccount.userAccount?.name, color: UIColor.lightGrayColor(), fontsize: 13)
        titleView.addSubview(titleLable)
        titleView.addSubview(nameLable)
        
        titleLable.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLable.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView=titleView
        
    }
    
    private lazy var textView:UITextView = {
        
        let textView=UITextView()
        textView.delegate=self
        textView.font=UIFont.systemFontOfSize(15)
        textView.textColor=UIColor.darkGrayColor()
        textView.alwaysBounceVertical=true
        textView.keyboardDismissMode=UIScrollViewKeyboardDismissMode.OnDrag
        return textView
    }()
   private lazy var toolBar=UIToolbar()
    
    private lazy var placeHolder:UILabel=UILabel(title: "分享微博...", color:UIColor.lightGrayColor(), fontsize: 15)
    private lazy var pictureSelectorVC=PictureSelectorViewController()
    
    private lazy var tipLable:UILabel = UILabel(title: nil, color: UIColor.darkGrayColor(), fontsize: 14)


}
